import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      component: () => import('../views/login/index.vue'),
      meta: { title: '登录', requiresAuth: false }
    },
    {
      path: '/register',
      component: () => import('../views/register/index.vue'),
      meta: { title: '注册', requiresAuth: false }
    },
    {
      path: '/',
      component: () => import('../views/dashboard/index.vue'),
      meta: { title: '首页', requiresAuth: true }
    },
    {
      path: '/cases',
      component: () => import('../views/cases/index.vue'),
      meta: { title: '用例管理', requiresAuth: true }
    },
    {
      path: '/execution',
      component: () => import('../views/execution/index.vue'),
      meta: { title: '执行管理', requiresAuth: true }
    },
    {
      path: '/reports',
      component: () => import('../views/reports/index.vue'),
      meta: { title: '报告分析', requiresAuth: true }
    },
    {
      path: '/settings',
      component: () => import('../views/settings/index.vue'),
      meta: { title: '系统设置', requiresAuth: true }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 自动化测试平台`
  }

  const userStore = useUserStore()
  
  // 判断该路由是否需要登录权限
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 需要登录权限但用户未登录，跳转到登录页
    if (!userStore.isLoggedIn()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 保存原本想访问的路径
      })
    } else {
      next() // 用户已登录，放行
    }
  } else {
    // 不需要登录权限的页面，直接放行
    next()
  }
})

export default router 